<template>
  <a-drawer
    :title="$t('modules.AllocateModal.125243-0')"
    :visible="visible"
    :destroyOnClose="true"
    :maskClosable="false"
    :width="400"
    :body-style="{
      paddingBottom: '80px',
      boxSizing: 'border-box',
      overflowY: 'auto',
    }"
    @close="onCloseDrawer"
  >
    <template v-if="isBatch">
      <a-alert :message="$t('modules.AllocateModal.125243-1')" type="warning" />
      <a-row justify="space-between" align="middle" style="padding: 10px 0">
        <div style="font-size: 16px">{{ $t('modules.AllocateModal.125243-2') }}</div>
        <a-checkbox
          v-model:checked="checkAll"
          :indeterminate="indeterminate"
          @change="onCheckAllChange"
        >
          {{ $t('modules.AllocateModal.125243-3') }}
        </a-checkbox>
      </a-row>
      <a-checkbox-group v-model:value="checked_admins" style="width: 100%">
        <a-row>
          <a-col
            :span="24"
            v-for="(item, index) of personnelList"
            :key="index"
            style="padding: 8px 0"
          >
            <a-checkbox :value="item.id" :disabled="item.disabled">{{ item.name }}</a-checkbox>
          </a-col>
        </a-row>
      </a-checkbox-group>
    </template>
    <template v-else>
      <a-form ref="formRef" layout="vertical" :model="formState" @finish="onSubmit">
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item :label="$t('modules.AllocateModal.125243-4')" name="user_uid">
              <a-select
                v-model:value="formState.user_uid"
                style="width: 100%"
                allow-clear
                :placeholder="$t('modules.AllocateModal.125243-5')"
                :options="adminList"
                :fieldNames="{
                  label: 'realname',
                  value: 'uid',
                }"
                @click="addAdmin(formState.user_uid, 'user_name')"
                :open="false"
              >
              </a-select>
            </a-form-item>
          </a-col>
          <div class="part-title">
            <div class="flex align-center">
              <div class="part-title-text">{{ $t('modules.AllocateModal.125243-6') }}</div>
              <div style="margin-left: 10px; color: #999">
                {{ $t('modules.AllocateModal.125243-7') }}
              </div>
            </div>
          </div>
          <a-col v-if="type == 1" :span="24">
            <a-form-item :label="$t('modules.AllocateModal.125243-8')" name="name">
              <a-tree-select
                v-model:value="formState.department"
                style="width: 100%"
                :dropdown-style="{maxHeight: '400px', overflow: 'auto'}"
                :tree-data="departmentList"
                :placeholder="$t('modules.AllocateModal.125243-5')"
                :fieldNames="replaceFieldsDepartment"
                allowClear
                labelInValue
                tree-checkable
                :treeCheckStrictly="true"
                :maxTagCount="2"
              >
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col v-if="type == 1" :span="24">
            <!-- 资产分类 -->
            <a-form-item :label="$t('modules.AllocateModal.125243-9')" name="property_type">
              <a-tree-select
                v-model:value="formState.property_type"
                style="width: 100%"
                :placeholder="$t('modules.AllocateModal.125243-5')"
                :dropdown-style="{maxHeight: '400px', overflow: 'auto'}"
                :tree-data="propertyTypeList"
                :fieldNames="replaceFieldsCategory"
                allowClear
                labelInValue
                tree-checkable
                :treeCheckStrictly="true"
                :maxTagCount="2"
              >
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col v-if="type == 1" :span="24">
            <a-form-item :label="$t('modules.AllocateModal.125243-10')" name="position">
              <a-select
                v-model:value="formState.position"
                :placeholder="$t('modules.AllocateModal.125243-5')"
                style="width: 100%"
                mode="multiple"
                :options="
                  positionList.map((item) => ({
                    label: item.name,
                    value: item.id,
                  }))
                "
                allow-clear
                labelInValue
                :maxTagCount="2"
              >
              </a-select>
            </a-form-item>
          </a-col>

          <a-col v-if="type != 1" :span="24">
            <a-form-item :label="$t('modules.AllocateModal.125243-11')" name="position">
              <a-select
                v-model:value="formState.company_id"
                :placeholder="$t('modules.AllocateModal.125243-5')"
                style="width: 100%"
                :options="orgBranchList"
              >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </template>

    <div class="drawer-footer">
      <a-button class="mr-10" @click="onCloseDrawer">{{ $t('common.button.cancel') }}</a-button>
      <a-button type="primary" @click="onSubmit">{{ $t('common.button.ok') }}</a-button>
    </div>

    <!-- 选择成员 -->
    <ChooseOrgMember
      @request="$utils.commonRequest"
      :visible="memberVisible"
      :deptDisabled="true"
      :uMax="1"
      setUids="uncheck"
      :getDetail="true"
      :uids="selectedUids"
      @close="handleAddMemberClose"
      @success="handleAddMemberSuccess"
    />
  </a-drawer>
</template>

<script>
import {computed, defineComponent, reactive, toRefs, toRaw, watch, toRef, ref} from 'vue'
import store from '../../../store'
import request from '../../../common/utils/request'
import {message, Steps, Step} from 'ant-design-vue'
import {DownOutlined} from '@ant-design/icons-vue'
import {TenantComponent, ChooseOrgMember, CustomTable} from 'k2-common-vue3'
import {t} from '@/locale'

export default defineComponent({
  name: 'AllocateModal',
  components: {ChooseOrgMember},
  props: {
    visible: {
      default: false,
      type: Boolean,
    },
    isBatch: {
      default: false,
      type: Boolean,
    },
    checkedIds: {
      type: Array,
      default: () => [],
    },
    type: {
      type: [Number, String],
      default: 1,
    },
    planCategoryIds: {
      type: Array,
    },
  },
  setup(props, context) {
    const state = reactive({
      userList: [],
      departmentList: [],
      replaceFieldsDepartment: {
        children: 'subcat',
        label: 'name',
        key: 'id',
        value: 'id',
      },
      propertyTypeList: [],
      replaceFieldsCategory: {
        children: 'subcat',
        label: 'category_name',
        key: 'id',
        value: 'id',
      },
      positionList: [],
      adminList: [],
      personnelList: [],
      checked_admins: [],
      orgBranchList: [],
      checkAll: false,
      indeterminate: false,
      memberVisible: false,
      selectedUids: [],
    })

    const formState = reactive({
      user_uid: undefined,
      department: undefined,
      property_type: undefined,
      position: undefined,
      company_id: undefined,
    })

    const getdepartmentList = () => {
      request.get('/org', '/department/index', {withUser: 1, status: 4}).then((res) => {
        state.personnelList = res.list[0].personal.map((item) => {
          return {
            name: item.realname,
            id: item.uid,
          }
        })

        // 已经选择过的人禁用
        console.log('props.checkedIds', props.checkedIds)
        if (props.checkedIds.length > 0) {
          state.personnelList.forEach((item) => {
            if (props.checkedIds.includes(item.id)) {
              item.disabled = true
            }
          })
          state.checked_admins = JSON.parse(JSON.stringify(props.checkedIds))
        }
      })
    }

    const addAdmin = (id, type) => {
      state.selectedUids = []
      if (id) {
        state.selectedUids = [id, ...props.checkedIds]
      } else {
        state.selectedUids = props.checkedIds
      }
      state.memberVisible = true
    }

    const handleAddMemberSuccess = (data) => {
      state.adminList = data.user
      formState.user_uid = data.user[0].uid
      state.memberVisible = false
    }

    const handleAddMemberClose = () => {
      state.memberVisible = false
    }

    // 获取基础信息(所属公司、购置方式、管理员、使用人列表)
    const getBasicInfo = () => {
      getdepartmentList()
      store.dispatch('GetBasic').then((list) => {
        if (list.orgList && list.orgList.length > 0) {
          state.orgList = list.orgList
        }
        if (list.purchaseType && list.purchaseType.length > 0) {
          state.purchaseTypeList = list.purchaseType
        }
        if (list.userList && list.userList.length > 0) {
          state.userList = list.userList.map((item) => {
            return {
              value: item.id,
              label: item.name,
            }
          })
        }
        if (list.status && list.status.length > 0) {
          state.propertyStatusList = list.status
        }
      })

      // 获取所在位置
      store.dispatch('GetLocation').then((list) => {
        if (list && list.length > 0) {
          state.positionList = list
        }
      })

      // 获取使用部门
      store.dispatch('GetDepartment').then((list) => {
        if (list && list.length > 0) {
          state.departmentList = list
        }
      })

      // 获取资产类别
      store.dispatch('GetPropertyType').then((list) => {
        if (list && list.length > 0) {
          list.map((item) => {
            if (item.subcat && item.subcat.length > 0) {
              item.selectable = false
            }
          })

          if (props.planCategoryIds.length > 0) {
            const filterTree = (nodes) => {
              return nodes
                .map((node) => {
                  const newNode = {...node}
                  if (newNode.subcat) {
                    newNode.subcat = filterTree(newNode.subcat)
                  }
                  const inList = props.planCategoryIds.includes(newNode.id)
                  const hasChild = newNode.subcat && newNode.subcat.length > 0
                  return inList || hasChild ? newNode : null
                })
                .filter(Boolean)
            }
            state.propertyTypeList = filterTree(list)
          } else {
            state.propertyTypeList = list
          }
        }
      })
    }

    const onCheckAllChange = (e) => {
      let list = []
      state.personnelList.forEach((item) => {
        list.push(item.id)
      })

      if (e.target.checked) {
        state.checked_admins = list
      } else {
        if (props.checkedIds.length > 0) {
          state.checked_admins = JSON.parse(JSON.stringify(props.checkedIds))
        } else {
          state.checked_admins = []
        }
      }
      state.indeterminate = false
    }

    watch(
      () => state.checked_admins,
      (val) => {
        state.indeterminate = !!val.length && val.length < state.personnelList.length
        state.checkAll = val.length === state.personnelList.length
      }
    )

    const init = () => {
      getBasicInfo()
      let list = store.getters?.mainAppProps?.orgBranchOptions
      list.forEach((item) => {
        state.orgBranchList.push({
          value: item.id,
          label: item.name ? item.name : item.company,
        })
      })
    }

    init()

    const onCloseDrawer = () => {
      context.emit('onClose')
    }

    const onSubmit = () => {
      let result = {
        is_batch: props.isBatch ? 1 : 0,
      }
      if (props.isBatch) {
        if (!state.checked_admins.length) {
          message.error(t('modules.AllocateModal.125243-12'))
          return
        }
        let list = []
        state.personnelList.forEach((item) => {
          if (!item.disabled && state.checked_admins.includes(item.id)) {
            list.push({
              user_id: item.id,
              user_name: item.name,
            })
          }
        })
        result.list = list
      } else {
        if (!formState.user_uid) {
          message.error(t('modules.AllocateModal.125243-12'))
          return
        }
        state.adminList.forEach((item) => {
          if (item.uid == formState.user_uid) {
            result.user_name = item.realname
          }
        })

        result.user_id = formState.user_uid

        // 部门
        if (formState.department && formState.department.length > 0) {
          // result.department = formState.department;
          let names = formState.department.map((item) => item.label)
          result.departmentText = names.join('、')
          result.departmentIds = formState.department.map((item) => item.value)
        }
        // 资产分类
        if (formState.property_type && formState.property_type.length > 0) {
          // result.property_type = formState.property_type;
          let names = formState.property_type.map((item) => item.label)
          result.typeText = names.join('、')
          result.typeIds = formState.property_type.map((item) => item.value)
        }
        // 资产位置
        if (formState.position && formState.position.length > 0) {
          // result.position = formState.position;
          let names = formState.position.map((item) => item.label)
          result.positionText = names.join('、')
          result.positionIds = formState.position.map((item) => item.value)
        }

        if (formState.company_id) {
          state.orgBranchList.forEach((item) => {
            if (item.value == formState.company_id) {
              result.company_name = item.label
              result.company_id = item.value
            }
          })
        }
      }
      context.emit('onSubmit', result)
    }

    return {
      t,
      ...toRefs(state),
      onSubmit,
      onCloseDrawer,
      formState,
      onCheckAllChange,
      addAdmin,
      handleAddMemberSuccess,
      handleAddMemberClose,
    }
  },
})
</script>

<style lang="less" scoped>
.flex {
  display: flex;
}

.align-center {
  align-items: center;
}

.space-between {
  justify-content: space-between;
}

.part-title {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f1f1f1;
  padding-bottom: 5px;
  margin-bottom: 20px;

  .part-title-text {
    position: relative;
    font-size: 16px;
    padding: 0 5px;
    font-weight: bold;

    &::after {
      content: '';
      display: block;
      background-color: #1890ff;
      width: 100%;
      height: 2px;
      position: absolute;
      bottom: -6px;
      left: 0;
      border-radius: 4px;
    }
  }
}
</style>
